<?php
/**
 * DanMVC
 * 
 * 
 */



define('BASE_PATH', dirname(__FILE__));

$requestUrl = $_SERVER['REQUEST_URI'];

$projectDirectory = implode('/', array_intersect(explode('/', $requestUrl), explode('/', str_replace('\\', '/', BASE_PATH))));
if ($projectDirectory[strlen($projectDirectory)-1] != '/') {
        $projectDirectory = '/' . $projectDirectory . '/';
}





define('PROJECT_DIR', $projectDirectory);

$baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . PROJECT_DIR;

define('BASE_URL', $baseUrl);


require_once 'config/routes.php';
require_once 'config/config.php';


$requestUrl = str_replace(PROJECT_DIR, '', $requestUrl);

$route = preg_replace('/\?.*/', '', $requestUrl);


$full_array_uri = preg_split('[\\/]',$route, -1, PREG_SPLIT_NO_EMPTY);


//Check routing

foreach($routes as $pattern => $value){
    $pattern = str_replace('/', '\/', $pattern);
    $pattern = '/^' . $pattern . '/';
    $pattern = str_replace("*", "(.*?)", $pattern);
    $pattern = str_replace(":num", "([0-9]+)", $pattern);
 
    if(preg_match($pattern, $route)){
        $route = $value;
        break;
    }
}

//check for nested controller
$controller = '';
$action = false;


$array_uri = preg_split('[\\/]',$route, -1, PREG_SPLIT_NO_EMPTY);

$checkDir = BASE_PATH . "/app/controller";

foreach($array_uri as $key => $value){
    $checkDir .= '/' . strtolower($value);

    if(!file_exists($checkDir)){
        if(isset($array_uri[$key])){
            $controller .= $array_uri[$key];
        }
        
        if(isset($array_uri[$key + 1])){
            $action = $array_uri[$key + 1];
        }
        break; //end foreach
    } else {
        $controller .= strtolower($value) . '/';
    }
    
}

if(empty($controller)){
    $controller = DEFAULT_CONTROLLER;
}


//Load Base Librarys

$libDir = BASE_PATH . "/lib/";

//if ($openPath = opendir($libDir)) {
//    while (false !== ($file = readdir($openPath))) {
//        if(preg_match("/(.*?)\.php/", $file)){
//            require_once $libDir . $file;
//        }
//    }
//    closedir($openPath);
//}

require_once('lib/Exceptions/HttpCodeException.php');
require_once('lib/Exceptions/ViewException.php');
require_once('lib/Exceptions/LoaderException.php');

require_once('lib/Session.php');
require_once('lib/Input.php');
require_once('lib/Loader.php');
require_once('lib/Cookie.php');
require_once('lib/Uri.php');
require_once('lib/App.php');
require_once('lib/Controller.php');
require_once('lib/RestController.php');
require_once('lib/Database.php');

if($config['use_database']){
    $dataBase = Database::getInstance();
    $dataBase->connect(DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT);
}


$uri = new Uri();
$uri->setSegments($full_array_uri);

$application = new App();
$application->setUri($uri);

try{
    $application->loadController($controller, $action);
}catch(HttpCodeException $e){
    header($e->getMessage());
    echo $e->getMessage();
}catch(Exception $e){
    /* @var $e Exception */
    echo  '<strong>' . $e->getMessage() . '</strong>';
    echo $e->getTraceAsString();
}